package com.ruoyi.charge.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.charge.bo.EquipmentBatchAddBo;
import com.ruoyi.charge.service.WXService;
import com.ruoyi.common.enums.DeletedStatus;
import com.ruoyi.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.ruoyi.charge.bo.EquipmentAddBo;
import com.ruoyi.charge.bo.EquipmentQueryBo;
import com.ruoyi.charge.bo.EquipmentEditBo;
import com.ruoyi.charge.domain.Equipment;
import com.ruoyi.charge.mapper.EquipmentMapper;
import com.ruoyi.charge.vo.EquipmentVo;
import com.ruoyi.charge.service.IEquipmentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 充电设备管理Service业务层处理
 *
 * @author fanqie
 * @date 2021-10-25
 */
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements IEquipmentService {

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private WXService wxService;

    @Override
    public EquipmentVo queryById(Long equipmentId) {
        Equipment db = this.baseMapper.selectById(equipmentId);
        return BeanUtil.toBean(db, EquipmentVo.class);
    }

    @Override
    public List<EquipmentVo> queryList(EquipmentQueryBo bo) {
        LambdaQueryWrapper<Equipment> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getEquipmentNumber()), Equipment::getEquipmentNumber, bo.getEquipmentNumber());
        lqw.eq(bo.getStoreId() != null, Equipment::getStoreId, bo.getStoreId());
        return entity2Vo(this.list(lqw));
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<EquipmentVo> entity2Vo(Collection<Equipment> collection) {
        List<EquipmentVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, EquipmentVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Equipment> page = (Page<Equipment>) collection;
            Page<EquipmentVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(EquipmentAddBo bo) {
        Equipment add = BeanUtil.toBean(bo, Equipment.class);
        String equipmentNumber = bo.getEquipmentNumber();
        if (StringUtils.isNotBlank(equipmentNumber)) {

            if (this.getEquipmentByEquipmentNumber(equipmentNumber) != null) {
                throw new CustomException("设备号已存在，添加失败！");
            }
        }
        validEntityBeforeSave(add);
        return this.save(add);
    }

    /**
     * 根据设备号获取设备信息
     *
     * @param equipmentNumber
     * @return
     */
    private Equipment getEquipmentByEquipmentNumber(String equipmentNumber) {
        Equipment equipment = equipmentMapper.selectOne(
                new LambdaQueryWrapper<Equipment>().eq(Equipment::getEquipmentNumber, equipmentNumber)
                        .eq(Equipment::getDeleted, DeletedStatus.VALID.getCode())
                        .last("limit 1")
        );
        return equipment;
    }

    @Override
    public Boolean updateByEditBo(EquipmentEditBo bo) {
        Equipment update = BeanUtil.toBean(bo, Equipment.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Equipment entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }


    @Transactional
    @Override
    public Boolean batchInsert(EquipmentBatchAddBo bo) {
        List<String> list = bo.getEquipmentNumberList();
        if (list == null || list.size() == 0) {
            throw new CustomException("设备号列表为空！");
        }
        //校验设别号是否已经注册
        list.forEach(e -> {
            if (this.getEquipmentByEquipmentNumber(e) != null) {
                throw new CustomException("设备号：" + e + "已经存在，插入失败！");
            }
            Equipment insert = new Equipment();
            insert.setEquipmentNumber(e);
            this.save(insert);
        });
        return true;
    }

    @Override
    public Boolean distributeEquipment(Long equipmentId, Long storeId, String tableNumber) {

        Equipment equipment = this.getById(equipmentId);
        if (equipment == null) {
            throw new CustomException("设备id 不存在！");
        }
        if (equipment.getStoreId() != null && equipment.getStoreId() != 0) {
            throw new CustomException("该设备已分配，无法再次分配");
        }
        Equipment update = new Equipment();
        update.setEquipmentId(equipmentId);
        update.setStoreId(storeId);
        update.setTableNumber(tableNumber);

        //生成二维码
        String qtcodeurl = wxService.generateQrcode(equipment.getEquipmentId(), storeId, tableNumber);
        update.setQrcodeUrl(qtcodeurl);

        this.updateById(update);
        return true;
    }

}
